import 'dart:ui';
import 'package:flutter/painting.dart';
import 'package:flutter/widgets.dart';
import 'package:hixing_app/views/test_view/test_matrix4/transform_vertex_model.dart';
import 'package:vector_math/vector_math_64.dart' as vector;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math' as math;
import 'package:get/get.dart';
import 'package:hixing_app/views/test_view/canvas_utils.dart';
import 'package:hixing_app/views/test_view/test_matrix4/rect_element_model.dart';

class ResetMatrix4 extends StatefulWidget {
  @override
  _ResetMatrix4State createState() => _ResetMatrix4State();
}

class _ResetMatrix4State extends State<ResetMatrix4> {
  List<RectInfoModel> rectList = [];
  CanvasEventType? eventType;

  // 平移
  double dx = 100;
  double dy = 100;

  // 缩放比例，用来计算宽高比例的
  double wProportion = 1;
  double hProportion = 1;

  // 平移
  // double scaleDx = 0;
  // double scaleDy = 0;

  // 触摸点dx跟dy坐标跟起始dx dy修正
  double odx = 0;
  double ody = 0;

  double scaleOdx = 0;
  double scaleOdy = 0;

  bool isLock = true;

  // 缩放
  double scaleX = 1;
  double scaleY = 1;

  // 缩放
  double? lockScaleX;

  double? lockScaleY;

  // 缩放的rect，
  Rect? scaleRenderRect;

  //svg  偏移量 ,用来计算触摸缩放的时候 点一下会放大的bug
  double correctSvgDx = 0;
  double correctSvgDy = 0;

  Size imgSize = Size(100, 100);
  Size iconSize = Size(30, 30);

  // 旋转
  double rotationAngle = 0.0;
  Offset initialPosition = Offset(0, 0);

  // 缩放前的图片尺寸
  double initScaleW = 0;
  double initScaleH = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SystemChrome.setPreferredOrientations(// 使设备横屏显示
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
  }

  tapImage() {
    //计算当前触摸的点到img原点的距离，对齐偏移量
    odx = initialPosition.dx - dx;
    ody = initialPosition.dy - dy;
  }

  tapScale() {
    //计算当前触摸的点到scale icon原点的距离，对齐偏移量
    // initScaleW = imgSize.width * scaleX;
    // initScaleH = imgSize.height * scaleY;
    // lockScaleX = scaleX;
    // lockScaleY = scaleY;
    // scaleOdx = initialPosition.dx - dx - (imgSize.width);
    // scaleOdy = initialPosition.dy - dy - (imgSize.height);
    odx = initialPosition.dx - dx - (imgSize.width * scaleX);
    ody = initialPosition.dy - dy - (imgSize.height * scaleY);
    print("点击缩放偏移量：${odx},$ody");
    // print("缩放后的尺寸x: $initScaleW,Y: $initScaleW");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   title: Text('模板'),
      // ),
      body: Stack(
        children: [
          Listener(
            onPointerDown: (details) {
              // 获取点击的位置
              final RenderBox renderBox =
                  context.findRenderObject() as RenderBox;
              // 需要初始值加上默认的偏移量
              final globalPosition =
                  renderBox.localToGlobal(details.localPosition);
              initialPosition = globalPosition;

              for (var element in rectList) {
                if (element.path != null) {
                  if (element.path!.contains(globalPosition)) {
                    eventType = element.type;
                    print("element event ：${element.type}");
                    if (eventType == CanvasEventType.image) {
                      tapImage();
                    } else if (eventType == CanvasEventType.scale) {
                      tapScale();
                    } else if (eventType == CanvasEventType.lock) {
                      isLock = !isLock;

                      if (isLock) {
                        imgSize = Size((imgSize.width * scaleX),
                            (imgSize.height * scaleY));
                        scaleX = 1;
                        scaleY = 1;
                      }
                      // else {
                      //   lockScaleX = null;
                      //   lockScaleY = null;
                      // }

                      setState(() {});
                    }
                    break;
                  }
                }
              }
            },
            onPointerUp: (_) {
              eventType = null;
              // lockScaleX = scaleX;
              // lockScaleY = scaleY;
              // initScaleW = imgSize.width * (scaleX);
              // initScaleH = imgSize.height * (scaleY);
              // print("抬起 设置初始化匡高:${initScaleW},$initScaleH");
            },
            onPointerMove: (details) {
              // 获取点击的位置
              final RenderBox renderBox =
                  context.findRenderObject() as RenderBox;
              // 需要初始值加上默认的偏移量
              final globalPosition =
                  renderBox.localToGlobal(details.localPosition);
              final newPosition = details.localPosition;
              final delta = newPosition - initialPosition;

              if (eventType == CanvasEventType.image) {
                // 平移元素操作
                setState(() {
                  dx = globalPosition.dx - odx;
                  dy = globalPosition.dy - ody;
                });
              } else if (eventType == CanvasEventType.scale) {
                Rect _rect;
                _rect = Rect.fromLTRB(
                    dx, dy, globalPosition.dx - odx, globalPosition.dy - ody);
                scaleX = _rect.width / imgSize.width;
                scaleY = _rect.height / imgSize.height;
                if (isLock) {
                  double computedScale = (scaleX + scaleY) / 2;
                  scaleX = computedScale;
                  scaleY = computedScale;
                }
                // scaleDx = globalPosition.dx - odx;
                // scaleDy = globalPosition.dy - ody;
                // 计算点位直接的距离，然后计算缩放的尺寸
                // print("缩放中,${dx},${globalPosition.dx - odx - imgSize.width}");
                // double resetScaleX;
                // double resetScaleY;
                // if (lockScaleX == null) {
                // scaleX = (globalPosition.dx - imgSize.width - scaleOdx) /
                //     (initialPosition.dx - dx);
                // scaleY = (globalPosition.dy - imgSize.height - scaleOdy) /
                //     (initialPosition.dy - dy);
                // print("缩放的值${scaleX},${scaleY}");
                // } else {
                //   resetScaleX = lockScaleX!;
                //   resetScaleY = lockScaleY!;
                // double _x =
                //     globalPosition.dx / (dx + (imgSize.width * lockScaleX!));
                // print("lockScaleX：${lockScaleX},_x: ${_x},");
                // print("${lockScaleX! + _x - 1}");

                // resetScaleX = (globalPosition.dx) /
                //     (dx + (imgSize.width * lockScaleX!));
                // resetScaleY =
                //     (globalPosition.dy) / (dy + imgSize.height * lockScaleY!);
                //
                // resetScaleX = lockScaleX! + (resetScaleX - 1); // 上次的
                // resetScaleY = lockScaleY! + (resetScaleY - 1); // 上次的
                // 上次的
                // }
                // } else {
                // resetScaleX = (globalPosition.dx -
                //         odx -
                //         (imgSize.width * lockScaleX!)) /
                //     dx;
                // resetScaleY = (globalPosition.dy -
                //         ody -
                //         (imgSize.height * lockScaleY!)) /
                //     dy;
                // resetScaleX = resetScaleX;
                // resetScaleY = resetScaleY;
                // }
                // scaleX = resetScaleX;
                // scaleY = resetScaleY;

                // scaleX = lockScaleX + scaleX;
                // scaleY = lockScaleY + scaleY;
                // if (lockScaleX != 1 && lockScaleY != 1) {
                //   scaleX = scaleX + lockScaleX;
                //   scaleY = scaleY + lockScaleY;
                // }

                setState(() {});
              } else if (eventType == CanvasEventType.rotate) {
                // 求出当前坐标的方位角
                final angle = math.atan2(delta.dy, delta.dx);

                // final rotationFactor = 0.01;
                // final angle = math.atan2(delta.dy, delta.dx) * rotationFactor;

                if (initialPosition != null) {
                  setState(() {
                    rotationAngle = angle;
                  });
                }
              }
            },
            child: CustomPaint(
              size: Size.infinite,
              painter: MyCustomPainter(
                  rotationAngle: rotationAngle,
                  isLock: isLock,
                  // lockScaleX: lockScaleX,
                  // lockScaleY: lockScaleY,
                  iconSize: iconSize,
                  scaleX: scaleX,
                  scaleY: scaleY,
                  imgSize: imgSize,
                  rectList: rectList,
                  wProportion: wProportion,
                  hProportion: hProportion,
                  dx: dx,
                  dy: dy),
            ),
          ),
          Positioned(
              top: 30,
              left: 30,
              child: Container(
                decoration: BoxDecoration(
                    color: Colors.black26,
                    borderRadius: BorderRadius.circular(40)),
                child: IconButton(
                  onPressed: () {
                    Get.back();
                  },
                  icon: Icon(
                    Icons.arrow_back,
                    color: Colors.yellowAccent,
                    size: 30,
                  ),
                ),
              )),
          Positioned(
            top: 30,
            left: 130,
            child: Container(
              decoration: BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.circular(40)),
              child: Text("${isLock ? "锁定" : "不锁定"}"),
            ),
          )
        ],
      ),
    );
  }
}

class MyCustomPainter extends CustomPainter {
  MyCustomPainter(
      {this.rectList = const [],
      required this.dx,
      required this.dy,
      required this.scaleX,
      required this.scaleY,
      // required this.lockScaleX,
      // required this.lockScaleY,
      required this.imgSize,
      required this.isLock,
      required this.iconSize,
      required this.wProportion,
      required this.hProportion,
      required this.rotationAngle});

  List<RectInfoModel> rectList;

  late TransformVertexModel transformVertex;

  final double dx;
  final double dy;
  final double rotationAngle;
  final bool isLock;
  final double scaleX;
  final double scaleY;

  // final double lockScaleX;
  // final double lockScaleY;
  final Size imgSize;
  final Size iconSize;
  final double dz = 1;

  final double hProportion;

  final double wProportion;

  // 定义缩放变量
  // final double scaleX = 1;
  // final double scaleY = 1;
  final double scaleZ = 1;

  @override
  void paint(Canvas canvas, Size size) {
    rectList.clear();

    // 平移矩阵：最后一列的 [dx,dy,dz,1]
    //         [
    //           1,   0,   0,   0,
    //           0,   1,   0,   0,
    //           0,   0,   1,   0,
    //           dx,  dy,  dz,  1   // 注意这里的50
    //         ]
    //

    // 缩放矩阵
    //         [
    //           sx,   0,   0,   0,
    //           0,   sy,   0,   0,
    //           0,   0,   sz,   0,
    //           0,   0,   0,   1
    //         ]

    // 旋转矩阵
    //围绕z轴
    //   顺时针
    //         [
    //           cos(angle),   sin(angle),    0,   0,
    //           -sin(angle),   cos(angle),   0,   0,
    //           0,                    0,     1,   0,
    //           0,                    0,     0,   1
    //         ]
    //   逆时针
    //         [
    //           cos(angle),   -sin(angle),   0,   0,
    //           sin(angle),   cos(angle),    0,   0,
    //           0,                    0,     1,   0,
    //           0,                     0,     0,   1
    //         ]
    // 围绕X轴
    //   顺时针
    //        [
    //          1,           0,          0,         0,
    //          0,  cos(angle),   sin(angle),       0,
    //          0, -sin(angle),   cos(angle),       0,
    //          0,           0,            0,       1
    //        ]
    //
    //   逆时针
    //        [
    //          1,           0,          0,         0,
    //          0,  cos(angle),   -sin(angle),      0,
    //          0,  sin(angle),   cos(angle),       0,
    //          0,           0,            0,       1
    //        ]

    // 围绕Y轴
    //   顺时针
    //     [
    //       1,           0,          0,         0,
    //       0,  cos(angle),   sin(angle),       0,
    //       0, -sin(angle),   cos(angle),       0,
    //       0,           0,            0,       1
    //     ]
    //
    //   逆时针
    //     [
    //       1,           0,          0,         0,
    //       0,  cos(angle),   -sin(angle),      0,
    //       0,  sin(angle),   cos(angle),       0,
    //       0,           0,            0,       1
    //     ]
    rectList.clear();
    // TODO: implement paint
    // print("size：${size}");
    Paint _paint = Paint();
    CanvasUtils.drawGrid(canvas, _paint, size);
    CanvasUtils.drawCoor(canvas, _paint, size);
    canvas.save();
    Size proportionSize = imgSize;
    // 平移，定住左上角缩放
    // canvas.translate(dx, dy);
    // 锁定的话，先缩放宽高比例
    // if (isLock) {
    //   proportionSize =
    //       Size(imgSize.width * wProportion, imgSize.height * hProportion);
    //   print(
    //       "锁定后计算的宽高比例：${wProportion},${imgSize.width * wProportion},$hProportion,${imgSize.height * hProportion}");
    // }
    // print("缩放尺寸：scalex：${scaleX},${lockScaleX},scaleY：${scaleY},${scaleY}");
    Matrix4 matrix4 = Matrix4.identity();
    matrix4.translate(dx, dy);
    matrix4.scale(scaleX, scaleY);

    matrix4.rotateZ(rotationAngle);

    // matrix4.rotateZ(0.75);
    Rect _imgRect = Rect.fromLTWH(0, 0, imgSize.width, imgSize.height);
    canvas.translate(_imgRect.center.dx, _imgRect.center.dy);
    canvas.transform(matrix4.storage);
    canvas.translate(-_imgRect.center.dx, -_imgRect.center.dy);
    // matrix4.scale(scaleX, scaleY);
    // canvas.translate(-dx, -dy);
    // 绘制使用0，0为原点，imgTap使用准确的坐标，这样可以方便矩形事件点击判断
    canvas.drawRect(_imgRect, _paint..color = Colors.red);
    canvas.restore();

    // 获取大矩形 旋转后的顶点
    vector.Vector4 topLef = vector.Vector4(
        -imgSize.width / 2, -imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;
    vector.Vector4 topRight = vector.Vector4(
        imgSize.width / 2, -imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;

    vector.Vector4 bottomRight = vector.Vector4(
        imgSize.width / 2, imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;
    vector.Vector4 bottomLeft = vector.Vector4(-imgSize.width / 2,
        imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;r3表示一个点;

    vector.Vector4 topLeftPosition = matrix4.transformed(topLef);
    vector.Vector4 topRightPosition = matrix4.transformed(topRight);
    vector.Vector4 bottomRightPosition = matrix4.transformed(bottomRight);
    vector.Vector4 bottomLeftPosition = matrix4.transformed(bottomLeft);
    transformVertex = TransformVertexModel(
      topLeft: Offset(topLeftPosition.x, topLeftPosition.y),
      topRight: Offset(topRightPosition.x, topRightPosition.y),
      bottomRight: Offset(bottomRightPosition.x, bottomRightPosition.y),
      bottomLeft: Offset(bottomLeftPosition.x, bottomLeftPosition.y),
    );
    // canvas.save();

    // 实际渲染的矩形域点击坐标
    //
    // Rect _lockRect = Rect.fromLTWH(dx + topLeftPosition.x - 30,
    //     dy + topLeftPosition.y - 30, iconSize.width, iconSize.height);
    // canvas.drawRect(_lockRect, _paint..color = Colors.orange);
    // rectList.add(RectInfoModel(rect: _lockRect, type: CanvasEventType.lock));
    //
    // Rect _scaleRect = Rect.fromLTWH(dx + bottomRightPosition.x,
    //     dy + bottomRightPosition.y, iconSize.width, iconSize.height);
    // canvas.drawRect(_scaleRect, _paint..color = Colors.pink);
    // rectList.add(RectInfoModel(rect: _scaleRect, type: CanvasEventType.scale));
    // Rect _imgTapRect = Rect.fromPoints(
    //     Offset(topLeftPosition.x + dx + 300, topLeftPosition.y + dy),
    //     Offset(bottomRightPosition.x + dx + 300, bottomRightPosition.y + dy));
    // //
    // canvas.drawRect(_imgTapRect, _paint..color = Colors.green);
    // rectList.add(RectInfoModel(rect: _imgTapRect, type: CanvasEventType.image));

    // 绘制图片操作框
    drawImgActionBox(canvas, _paint);

    //绘制旋转icon
    drawRotateIcon(canvas, _paint, topRightOffset: transformVertex.topRight);

    // 绘制缩放按钮
    drawScaleIcon(canvas, _paint,
        bottomRightOffset: transformVertex.bottomRight);

    //绘制锁定
    drawLockIcon(canvas, _paint, topLeftOffset: transformVertex.topLeft);

    //绘制删除
    drawDeleteIcon(canvas, _paint,
        bottomLeftOffset: transformVertex.bottomLeft);

    // canvas.restore();
  }

  drawImgActionBox(Canvas canvas, Paint paint) {
    Path imgBoxPath = Path()
      ..moveTo(
          transformVertex.topLeft.dx, transformVertex.topLeft.dy); // 移动到第一个顶点
    imgBoxPath
      ..lineTo(transformVertex.topRight.dx, transformVertex.topRight.dy)
      ..lineTo(transformVertex.bottomRight.dx, transformVertex.bottomRight.dy)
      ..lineTo(transformVertex.bottomLeft.dx, transformVertex.bottomLeft.dy);
    imgBoxPath.close(); // 封闭路径

// 将路径的起点移动到指定位置 使用path.shift的方式修正偏移量，这里的起始点是原点距离矩形的正常距离，shift方法修正了偏移量,所以上面判断的时候，屏幕触摸的dx跟dy都不需要减去偏移量也不需要处理矩形中心点位移的情况
    imgBoxPath = imgBoxPath.shift(
        Offset(dx + (imgSize.width / 2), dy + (imgSize.height / 2)) +
            Offset(200, 0));
//     rotatePath = rotatePath.shift(_center);
    // 绘制矩形
    paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    canvas.drawPath(imgBoxPath, paint);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: imgBoxPath, type: CanvasEventType.image));
  }

  drawDeleteIcon(Canvas canvas, Paint paint,
      {required Offset bottomLeftOffset}) {
    final count = canvas.getSaveCount();
    canvas.save();
    // Rect _Rect = Rect.fromLTWH(
    //     dx + (imgSize.width / 2) + bottomLeftOffset.dx,
    //     dy + (imgSize.height / 2) + bottomLeftOffset.dy,
    //     iconSize.width,
    //     iconSize.height);
    // _Rect = _Rect.shift(Offset(-iconSize.width, 0));
    // // _rotateRect.shift(Offset(100, 100));
    // canvas.drawRect(_Rect, paint..color = Colors.red);
    // rectList.add(RectInfoModel(rect: _Rect, type: CanvasEventType.scale));

    Path _rectPath = Path()
      ..moveTo(-iconSize.width, iconSize.height); // 移动到第一个顶点
    _rectPath
      ..relativeLineTo(iconSize.width, 0)
      ..relativeLineTo(0, -iconSize.height)
      ..relativeLineTo(-iconSize.width, 0);
    _rectPath.close(); // 封闭路径

    _rectPath = _rectPath.transform(Matrix4.rotationZ(rotationAngle).storage);
    // canvas.translate(dx + bottomLeftOffset.dx + (imgSize.width / 2),
    //     (dy + bottomLeftOffset.dy + (imgSize.height / 2)));
    Offset boxVertex = Offset(dx + bottomLeftOffset.dx + (imgSize.width / 2),
        (dy + bottomLeftOffset.dy + (imgSize.height / 2)));
    _rectPath = _rectPath.shift(boxVertex);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: _rectPath, type: CanvasEventType.delete));
    // 绘制矩形
    paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    canvas.drawPath(_rectPath, paint);

    // 绘制svg
    canvas.saveLayer(null, paint);
    canvas.translate(boxVertex.dx, boxVertex.dy);
    canvas.rotate(rotationAngle);
    Rect svgRect = Rect.fromCenter(
        center: Offset(iconSize.width / 2, iconSize.height / 2),
        width: 20,
        height: 20);
    canvas.translate(-iconSize.width, 0);
    canvas.drawRect(svgRect, paint..color = Colors.purple);

    canvas.restoreToCount(count);
  }

  drawLockIcon(Canvas canvas, Paint paint, {required Offset topLeftOffset}) {
    final count = canvas.getSaveCount();
    canvas.save();
    // Rect _Rect = Rect.fromLTWH(
    //     dx + (imgSize.width / 2) + topLeftOffset.dx,
    //     dy + (imgSize.height / 2) + topLeftOffset.dy,
    //     iconSize.width,
    //     iconSize.height);
    // _Rect = _Rect.shift(Offset(-iconSize.width, 0));
    // // _rotateRect.shift(Offset(100, 100));
    // canvas.drawRect(_Rect, paint..color = Colors.red);
    // rectList.add(RectInfoModel(rect: _Rect, type: CanvasEventType.scale));

    Path _rectPath = Path()..moveTo(-iconSize.width, 0); // 移动到第一个顶点
    _rectPath
      ..relativeLineTo(iconSize.width, 0)
      ..relativeLineTo(0, -iconSize.height)
      ..relativeLineTo(-iconSize.width, 0);
    _rectPath.close(); // 封闭路径

    _rectPath = _rectPath.transform(Matrix4.rotationZ(rotationAngle).storage);
    // canvas.translate(dx + topLeftOffset.dx + (imgSize.width / 2),
    //     (dy + topLeftOffset.dy + (imgSize.height / 2)));
    Offset boxVertex = Offset(dx + topLeftOffset.dx + (imgSize.width / 2),
        (dy + topLeftOffset.dy + (imgSize.height / 2)));
    _rectPath = _rectPath.shift(boxVertex);

    // 绘制矩形
    paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    canvas.drawPath(_rectPath, paint);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: _rectPath, type: CanvasEventType.lock));

    // 绘制svg
    canvas.saveLayer(null, paint);
    canvas.translate(boxVertex.dx, boxVertex.dy);

    canvas.rotate(rotationAngle);
    Rect svgRect = Rect.fromCenter(
        center: Offset(iconSize.width / 2, iconSize.height / 2),
        width: 20,
        height: 20);
    canvas.translate(-iconSize.width, -iconSize.height);
    canvas.drawRect(svgRect, paint..color = Colors.purple);

    canvas.restoreToCount(count);
  }

  drawScaleIcon(Canvas canvas, Paint paint,
      {required Offset bottomRightOffset}) {
    final count = canvas.getSaveCount();
    canvas.save();
    // Rect _Rect = Rect.fromLTWH(
    //     dx + (imgSize.width / 2) + bottomRightOffset.dx,
    //     dy + (imgSize.height / 2) + bottomRightOffset.dy,
    //     iconSize.width,
    //     iconSize.height);
    // _Rect = _Rect.shift(Offset(0, -iconSize.height));
    // _rotateRect.shift(Offset(100, 100));
    // canvas.drawRect(_Rect, paint..color = Colors.red);
    // rectList.add(RectInfoModel(rect: _Rect, type: CanvasEventType.scale));

    Path _rectPath = Path()..moveTo(0, iconSize.height); // 移动到第一个顶点
    _rectPath
      ..relativeLineTo(iconSize.width, 0)
      ..relativeLineTo(0, -iconSize.height)
      ..relativeLineTo(-iconSize.width, 0);
    _rectPath.close(); // 封闭路径

    _rectPath = _rectPath.transform(Matrix4.rotationZ(rotationAngle).storage);
    // canvas.translate(dx + bottomRightOffset.dx + (imgSize.width / 2),
    //     (dy + bottomRightOffset.dy + (imgSize.height / 2)));
    Offset boxVertex = Offset(dx + bottomRightOffset.dx + (imgSize.width / 2),
        (dy + bottomRightOffset.dy + (imgSize.height / 2)));
    _rectPath = _rectPath.shift(boxVertex);
    // 绘制矩形
    paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    canvas.drawPath(_rectPath, paint);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: _rectPath, type: CanvasEventType.scale));

    // 绘制svg
    canvas.saveLayer(null, paint);
    canvas.translate(boxVertex.dx, boxVertex.dy);
    canvas.rotate(rotationAngle);
    Rect svgRect = Rect.fromCenter(
        center: Offset(iconSize.width / 2, iconSize.height / 2),
        width: 20,
        height: 20);
    canvas.drawRect(svgRect, paint..color = Colors.purple);

    canvas.restoreToCount(count);
  }

  drawRotateIcon(Canvas canvas, Paint paint, {required Offset topRightOffset}) {
    final count = canvas.getSaveCount();
    canvas.save();
    // Rect _rect = Rect.fromLTWH(
    //     dx + (imgSize.width / 2) + topRightOffset.dx,
    //     dy + (imgSize.height / 2) + topRightOffset.dy,
    //     iconSize.width,
    //     iconSize.height);
    // _rotateRect.shift(Offset(100, 100));
    // canvas.drawRect(_rect, paint..color = Colors.redAccent);
    // rectList.add(RectInfoModel(rect: _rect, type: CanvasEventType.rotate));

    Path _rectPath = Path()..moveTo(0, 0); // 移动到第一个顶点
    _rectPath
      ..relativeLineTo(iconSize.width, 0)
      ..relativeLineTo(0, -iconSize.height)
      ..relativeLineTo(-iconSize.width, 0);
    _rectPath.close(); // 封闭路径
    // canvas.translate(-iconSize.width / 2+100, -iconSize.height / 2+100);
    // canvas.translate(-iconSize.width / 2 + 100, -iconSize.height / 2 + 100);

    _rectPath = _rectPath.transform(Matrix4.rotationZ(rotationAngle).storage);

    // canvas.translate(dx + topRightOffset.dx + (imgSize.width / 2),
    //     (dy + topRightOffset.dy + (imgSize.height / 2)));
    Offset boxVertex = Offset(dx + topRightOffset.dx + (imgSize.width / 2),
        (dy + topRightOffset.dy + (imgSize.height / 2)));
    _rectPath = _rectPath.shift(boxVertex);

    // 绘制矩形
    paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    canvas.drawPath(_rectPath, paint);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: _rectPath, type: CanvasEventType.rotate));

    canvas.saveLayer(null, paint);
    canvas.translate(boxVertex.dx, boxVertex.dy);
    canvas.rotate(rotationAngle);
    // canvas.translate(0, -iconSize.height);

    Rect svgRect = Rect.fromCenter(
        center: Offset(iconSize.width / 2, iconSize.height / 2),
        width: 20,
        height: 20);
    svgRect = svgRect.shift(Offset(0, -iconSize.height));
    canvas.drawRect(svgRect, paint..color = Colors.purple);

    canvas.restoreToCount(count);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}

void drawVertexRect({
  scaleIconSize = const Size(30, 30),
  required Canvas canvas,
  required Paint paint,
  required double rotationAngle,
  CanvasEventType eventType = CanvasEventType.image,
  RotateVertexType vertexType = RotateVertexType.bottomRight,
  required List<RectInfoModel> rectList,
  // 对齐的顶点实际屏幕坐标
  required Offset originVertex,
}) {
  canvas.save();

  // 每次都以平移后的点为原点绘制
  // canvas.translate(dx, dy);

  /// 添加一个缩放的tap 使用旋转后的顶点+ 平移矩形中心旋转的偏移量
  double _scaleRectLeft = originVertex.dx;
  double _scaleRectTop = originVertex.dy;
  Rect scaleTapRect = Rect.fromLTRB(
      _scaleRectLeft, _scaleRectTop, _scaleRectLeft + 30, _scaleRectTop + 30);

  // 绘制矩形路径
  Size scaleIconSize = Size(30, 30);
  List<Offset> _scaleOffsetList =
      getRotatePoint(scaleIconSize, Offset.zero, rotationAngle);
  double _vertextX;
  double _vertextY;
  if (vertexType == RotateVertexType.bottomRight) {
    // 传入原始矩形是右下顶点，对齐左上顶点
    _vertextX = _scaleOffsetList[0].dx;
    _vertextY = _scaleOffsetList[0].dy;
  } else if (vertexType == RotateVertexType.topRight) {
    // 传入原始矩形是右上顶点，对齐左上顶点
    _vertextX = _scaleOffsetList[3].dx;
    _vertextY = _scaleOffsetList[3].dy;
  } else if (vertexType == RotateVertexType.topLeft) {
    _vertextX = _scaleOffsetList[2].dx;
    _vertextY = _scaleOffsetList[2].dy;
  } else {
    _vertextX = _scaleOffsetList[1].dx;
    _vertextY = _scaleOffsetList[1].dy;
  }
  // 计算原始矩形右下顶点跟操作按钮矩形的左上顶点, 两个顶点的偏移量，然后减去这个偏移量
  double _scaleIconOffsetX =
      originVertex.dx - (scaleTapRect.center.dx + _vertextX);
  double _scaleIconOffsetY =
      originVertex.dy - (scaleTapRect.center.dy + _vertextY);

  Path _scaleIconPath = Path()
    ..moveTo(_scaleOffsetList[0].dx, _scaleOffsetList[0].dy); // 移动到第一个顶点
  for (int i = 1; i < _scaleOffsetList.length; i++) {
    _scaleIconPath.lineTo(
        _scaleOffsetList[i].dx, _scaleOffsetList[i].dy); // 添加线段
  }
  _scaleIconPath.close(); // 封闭路径
  // 把偏移量加回去, 这样就可以对其顶点了
  _scaleIconPath = _scaleIconPath.shift(
      scaleTapRect.center + Offset(_scaleIconOffsetX, _scaleIconOffsetY));
  // 绘制矩形
  paint
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2.0;

  // canvas.translate(50, 200);
  canvas.drawPath(_scaleIconPath, paint);

  rectList.add(
      RectInfoModel(rect: Rect.zero, path: _scaleIconPath, type: eventType));

  canvas.restore();
}

List<Offset> getRotatePoint(Size imgSize, Offset center, double rotationAngle) {
  // double rotationAngle = math.pi / 3; // 旋转角度，单位为弧度

  // 计算矩形的中心点坐标
  // Offset center = Offset(0.0, 0.0); // 假设矩形中心点在原点

  // 计算每个顶点相对于中心点的坐标
  double halfWidth = imgSize.width / 2;
  double halfHeight = imgSize.height / 2;
  List<Offset> vertices = [
    Offset(-halfWidth, -halfHeight), // 左上角顶点
    Offset(halfWidth, -halfHeight), // 右上角顶点
    Offset(halfWidth, halfHeight), // 右下角顶点
    Offset(-halfWidth, halfHeight), // 左下角顶点
  ];

  // 应用旋转矩阵来计算旋转后的坐标
  List<Offset> rotatedVertices = [];
  for (var vertex in vertices) {
    double rotatedX = vertex.dx * math.cos(rotationAngle) -
        vertex.dy * math.sin(rotationAngle);
    double rotatedY = vertex.dx * math.sin(rotationAngle) +
        vertex.dy * math.cos(rotationAngle);
    rotatedVertices.add(Offset(rotatedX, rotatedY));
  }

  // 输出结果
  // print("旋转后的顶点坐标:");
  // for (var i = 0; i < vertices.length; i++) {
  // print("顶点${i + 1}: (${rotatedVertices[i].dx}, ${rotatedVertices[i].dy})");
  // }
  return rotatedVertices;
}

//
// List<Offset> getRotateVertices(
//   List<Offset> rectVertices,
//   Offset rectCenter,
//   double rotationAngle,
// ) {
//   final rotationMatrix = Matrix4.rotationZ(rotationAngle); // 构造旋转矩阵
// // 计算矩形旋转后的四个顶点的偏移量
//
//   //
//   // final rotatedRectVertices = rectVertices.map((vertex) {
//   //   final offset = vertex - rectCenter; // 计算相对于中心点的偏移量
//   //   final rotatedX = offset.dx * cosAngle - offset.dy * sinAngle; // 应用旋转矩阵
//   //   final rotatedY = offset.dx * sinAngle + offset.dy * cosAngle;
//   //   return Offset(rotatedX + rectCenter.dx, rotatedY + rectCenter.dy); // 计算旋转后的顶点位置
//   // }).toList();
// }

/// 通过计算旋转的坐标渲染旋转后的矩形
computedRotatePoint(Canvas canvas, Paint paint, Rect boxRect, Size imgSize,
    double rotationAngle) {
  canvas.save();
  Offset _center = Offset(boxRect.width / 2, boxRect.height / 2);

  //使用平移的方式修正偏移量，这里的起始点事原点，0，0
  // canvas.translate(_center.dx, _center.dy);

  // print("中心点：$_center");
  List<Offset> _rotateOffsetList =
      getRotatePoint(imgSize, _center, rotationAngle);

  //方案：获取旋转后的四个顶点，然后用path画出来，这时候有两个方案可以处理
  // 第一个方案：画布平移到矩形的中心点，因为drawPath 是以原点即是左上角为原点，所以在
  // 判断点击事件的时候，需要把触摸点的偏移量重置为原点，就是 localPosition - Offset(dx+imgSize/2,dy+imgSize/2),把之前的偏移量去掉，就是原点了,因为之前旋转的时候，位移到了矩形的原点位置，这里得加回去
  //
  // 第二个方案：更改path的起始点，path.shift方法，把path的起点位移到矩形的中心点，  这样的话，path就是没有偏移量计算的，因为在更改起点的时候，把dx跟dy加进去了，
  // 所以在判断点击事件的时候，需要把触摸点的偏移量重置为原点，就是 localPosition + Offset(dx,dy),把之前的偏移量加上，就是当前点击的位置了，因为之前判断矩形点击的时候，都是把 localPosition - Offset(dx,dy) 来判断的，这样矩形的原点以及判断的原点都是0，0开始的,
  // 或者直接用globalPosition    直接判断，不用之前减去偏移量的值，因为之前减去偏移量的值是为了判断计算矩形点击域减去的
  // 绘制矩形路径
  Path path = Path()
    ..moveTo(_rotateOffsetList[0].dx, _rotateOffsetList[0].dy); // 移动到第一个顶点
  for (int i = 1; i < _rotateOffsetList.length; i++) {
    path.lineTo(_rotateOffsetList[i].dx, _rotateOffsetList[i].dy); // 添加线段
  }
  path.close(); // 封闭路径
// 将路径的起点移动到指定位置 使用path.shift的方式修正偏移量，这里的起始点是原点距离矩形的正常距离，shift方法修正了偏移量,所以上面判断的时候，屏幕触摸的dx跟dy都不需要减去偏移量也不需要处理矩形中心点位移的情况
  path = path.shift(_center);
  // 绘制矩形
  paint
    ..color = Colors.blue
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2.0;
  canvas.drawPath(path, paint);
  // 这里的rect 以左上角 也就是（0，0） 为原点的，平移那些操作的原点是以offSet(dx,dy) 来做的，所以这里需要修正一下矩形的原点
  // Rect pathRect = path.getBounds();
  // canvas.drawRect(pathRect, _paint..color = Colors.blue);
  // Rect _correctRect = Rect.fromLTRB(pathRect.left - dx, pathRect.top - dy,
  //     pathRect.right - dx, pathRect.bottom - dy);
  // print("变换后的矩形：${path.getBounds()}");
  // rectList.add(RectInfoModel(
  //     rect: Rect.zero, path: path, type: CanvasEventType.image));

  canvas.restore();
}

enum RotateVertexType { topLeft, topRight, bottomRight, bottomLeft }
